import Taro, {Component, Config, InnerAudioContext, VideoContext} from '@tarojs/taro'
import {View, Image, Video, Slider} from '@tarojs/components'
import { SDBody } from 'sudao-ui'
import SDUtils from 'sudao-utils'

import './index.less'

import ListenIcon from '../../../images/ic_listen.png'
import VoiceIcon from '../../../images/ic_voice.png'

type IPageState = {
  mainIsLoading: boolean,
  articleData: any,
  audioCurrentSeconds: number,
  audioTotalSeconds: number,
  audioRatio: number,
  audioIsWaiting: boolean
}

export default class DiscoverDetailPage extends Component<{}, IPageState> {

  constructor() {
    super()
    this.setState({
      mainIsLoading: true,
      articleData: {},
      audioCurrentSeconds: 0,
      audioTotalSeconds: 0,
      audioRatio: 2,
      audioIsWaiting: false
    })
  }

  config: Config = {
    navigationBarTitleText: '详情',
    backgroundColor: '#fff'
  }

  videoContext: VideoContext | undefined = undefined
  audioContext: InnerAudioContext | undefined = undefined

  componentWillUnmount () {
    // @ts-ignore
    this.videoContext && this.videoContext.stop()
    this.audioContext && this.audioContext.stop()
    this.audioContext && this.audioContext.destroy()
  }

  componentDidMount () {
    this.videoContext = Taro.createVideoContext('articleVideoComps')

    this.audioContext = Taro.createInnerAudioContext()
    this.audioContext.onPlay(() => {
      console.log('开始播放')
    })
    this.audioContext.onTimeUpdate(() => {
      // @ts-ignore
      let duration: number = parseInt(`${this.audioContext.duration || 0}`)
      // @ts-ignore
      let currentTime: number = parseInt(`${this.audioContext.currentTime || 0}`)
      let ratio = (duration <= 0 ? 0 : currentTime / duration)
      ratio = ratio < 0.02 ? 0.02 : ratio
      ratio = ratio * 100
      this.setState({
        audioCurrentSeconds: currentTime,
        audioTotalSeconds: duration,
        audioRatio: ratio,
        audioIsWaiting: false
      })
    })
    this.audioContext.onWaiting(() => {
      console.log('等待中..')
      this.setState({
        audioIsWaiting: true
      })
    })
    this.audioContext.onCanplay(() => {
      console.log('可以播放...')
    })
    // @ts-ignore
    this.audioContext.onError((error) => {
      console.log(error)
    })
    let articleId = (this.$router.params || {}).articleId
    this.fetchData(articleId)
  }

  fetchData = async (articleId) => {
    let articleData = {}
    try {
      articleData = await SDUtils.doGet(`/content/wxmini/article/${articleId}`)
    } catch (e) {
      SDUtils.showMsg(e)
    } finally {
      this.setState({
        mainIsLoading: false,
        articleData: articleData
      })
    }
  }

  playAudio = () => {
    const { articleData = {} } = this.state
    let mediaUrl = articleData.mediaUrl
    if (!mediaUrl) { return }
    const innerAudioContext = this.audioContext
    // @ts-ignore
    innerAudioContext.src = mediaUrl
    // @ts-ignore
    innerAudioContext.play()
  }

  onSliderValueChanging = e => {
    // @ts-ignore
    if (!this.audioContext.paused) {
      // @ts-ignore
      this.audioContext.stop()
    }
    let value = parseFloat(e.detail.value) / 100
    const {audioTotalSeconds, articleData } = this.state
    let duration = audioTotalSeconds || parseFloat(articleData.audioTime || 0)
    duration = isNaN(duration) ? 0 : duration
    let currentTime = duration * value
    this.setState({
      audioCurrentSeconds: parseInt(`${currentTime}`)
    })
  }

  onSliderValueChange = e => {
    let value = parseFloat(e.detail.value) / 100
    const {audioTotalSeconds, articleData } = this.state
    let duration = audioTotalSeconds || parseFloat(articleData.audioTime || 0)
    duration = isNaN(duration) ? 0 : duration
    let currentTime = duration * value
    let mediaUrl = articleData.mediaUrl
    if (!mediaUrl) {
      currentTime = 0
    }
    let ratio = (duration <= 0 ? 0 : currentTime / duration)
    ratio = ratio < 0.02 ? 0.02 : ratio
    ratio = ratio * 100
    this.setState({
      audioCurrentSeconds: parseInt(`${currentTime}`),
      audioRatio: ratio
    }, () => {
      // @ts-ignore
      this.audioContext.src = mediaUrl
      // @ts-ignore
      this.audioContext.seek(currentTime)
      // @ts-ignore
      this.audioContext.play()
    })
  }

  render () {
    const { mainIsLoading, articleData = {}, audioCurrentSeconds, audioTotalSeconds, audioRatio, audioIsWaiting } = this.state

    let innerElement: JSX.Element | null = null
    if (articleData.articleType == 'TEXT') {
      innerElement = <View className="section-text">
        {
          articleData.coverImage ? (
            <View className="banner">
              <Image className="banner-img" lazyLoad mode='aspectFill' src={articleData.coverImage}></Image>
            </View>
          ) : null
        }
        <View className="header">
          <View className="title">{articleData.title}</View>
          <View className="sub-title">
            <View className="item">{SDUtils.formatDate(articleData.createTime,'yyyy-MM-dd HH:mm')}</View>
            <View className="item">浏览数：{articleData.viewTimes}</View>
          </View>
        </View>
      </View>
    } else if (articleData.articleType == 'VIDEO') {
      innerElement = <View className="section-video">
        <View className="banner">
          <Video id='articleVideoComps' src={articleData.mediaUrl} autoplay={false} poster={articleData.videoCoverImage} className='banner-video'></Video>
        </View>
        <View className="header">
          <View className="title">{articleData.title}</View>
          <View className="sub-title">
            <View className="item">{SDUtils.formatDate(articleData.createTime,'yyyy-MM-dd HH:mm')}</View>
            <View className="item">浏览数：{articleData.viewTimes}</View>
          </View>
        </View>
      </View>
    } else if (articleData.articleType == 'AUDIO') {
      innerElement = <View className="section-audio">
        <View className="audio-content">
          <View className="audio-section_top">
            <Image className="audio-tag_icon" src={ListenIcon}></Image>
            <View className="audio-tag_title">{articleData.viewTimes}</View>
          </View>
          <View className="audio-item">
            <Image className="audio-left" src={VoiceIcon} onClick={this.playAudio}></Image>
            <View className="audio-right">
              <View className="audio-title">品牌化运营、推广、优化</View>
              <Slider className="audio-slider" value={audioRatio} step={0.01} min={0} max={100} blockSize={7} backgroundColor='#E2E2E2' activeColor='#934900' onChanging={this.onSliderValueChanging} onChange={this.onSliderValueChange} />
              <View className="audio-bottom">
                <View className="audio-bottom_item">{SDUtils.formatDuration(audioCurrentSeconds)}</View>
                <View className="audio-bottom_item">
                  {
                    audioIsWaiting ? <View className="audio-bottom_progress weui-loading"></View> : null
                  }
                  <View className="audio-bottom_item">{SDUtils.formatDuration(audioTotalSeconds || articleData.audioTime)}</View>
                </View>
              </View>
            </View>
          </View>
        </View>
        <View className="audio-line"></View>
      </View>
    }

    return (
      <SDBody sd-class='container' loading={mainIsLoading}>
        { innerElement }
        {
          articleData.articleType == 'AUDIO' ? (
            <View className="audio-header">
              <View className="title-content">
                <View className="title">内容简介</View>
              </View>
              <View className="line"></View>
            </View>
            ) : null
        }
        <View className={`main-content ${articleData.articleType == 'AUDIO' ? 'main-content_audio' : ''}`}>
          {
            articleData.articleContent.map((item, index) => {
              return (
                item.type == 'IMAGE' ? (
                  <Image className="cell-item cell-item_img" src={item.content} mode='widthFix' lazyLoad key={index}></Image>
                ) : (
                  <View className="cell-item" key={index}>{item.content}</View>
                )
              )
            })
          }
        </View>
      </SDBody>
    )
  }
}
